package com.plian.system.service.hr.staff.impl;

import com.plian.Tools.CollectionUtil;
import com.plian.Tools.EncryptUtil;
import com.plian.Tools.StringUtil;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.dto.hr.staff.SupervisorDTO;
import com.plian.system.entity.hr.staff.StaffFiles;
import com.plian.system.entity.hr.staff.Supervisor;
import com.plian.system.mapper.hr.staff.SupervisorMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.R;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.service.hr.staff.IStaffFilesService;
import com.plian.system.service.hr.staff.ISupervisorService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.sys.user.ISysUserService;
import com.plian.system.service.yth.ISupervisoryBoardService;
import com.plian.system.vo.hr.staff.StaffFilesVO;
import com.plian.system.vo.hr.staff.SupervisorVO;
import com.plian.system.vo.report.HeaderVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.vo.report.ReportVO;
import com.plian.system.wrapper.hr.staff.StaffFilesWrapper;
import com.plian.system.wrapper.hr.staff.SupervisorWrapper;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.BaseConstant.BASE64_KEY;

;

/**
 * 监事会 服务实现类
 *
 * @author gangan
 * @since 2019-11-12
 */
@Service
@AllArgsConstructor
public class SupervisorServiceImpl extends BaseServiceImpl<SupervisorMapper, Supervisor> implements ISupervisorService {

    private IStaffFilesService staffFilesService;

    private StaffFilesWrapper staffFilesWrapper;

    private SupervisorWrapper supervisorWrapper;

    private ISupervisoryBoardService supervisoryBoardService;

    private IOrgService orgService;

    private ISysUserService userService;

    @Override
    public ReportReturnVO report(SupervisorDTO supervisorDTO) {
        ReportReturnVO reportReturnVO = new ReportReturnVO();
        ReportVO reportVO = new ReportVO();

        reportVO
                .addHeader(HeaderVO.builder().key("companyName").title("单位").build())
                .addHeader(HeaderVO.builder().key("staffName").title("姓名").build())
                .addHeader(HeaderVO.builder().key("isOutSupervisor").title("是否外派监事").build())
                .addHeader(HeaderVO.builder().key("supervisorPositionName").title("监事会职务").build())
                .addHeader(HeaderVO.builder().key("genderName").title("性别").build())
                .addHeader(HeaderVO.builder().key("birthday").title("出生日期").build())
                .addHeader(HeaderVO.builder().key("appointmentTime").title("任职时间").build());

        List<Supervisor> directors = baseMapper.reportDataPage(supervisorDTO.getCompanyIds(), supervisorDTO.getGenderIds(),
                supervisorDTO.getSupervisorPositionIds(), supervisorDTO.getIsOutSupervisor(), supervisorDTO.getStaffName());
        List<SupervisorVO> list = supervisorWrapper.entityToVO(directors);


        //给所有数据按照单位编码升序，人员编码升序
        list = list.parallelStream().sorted(Comparator.comparing(SupervisorVO::getCompanyCode).thenComparing(SupervisorVO::getCreateTime)).collect(Collectors.toList());
        List<SupervisorVO> resultData = new ArrayList<>() ;
        String companyNameSearchId = "";
        int count = 0;
        int sum = 0;
        for(int i =0;i< list.size();i++){
            if(!companyNameSearchId.equals(list.get(i).getCompanyId())){
                if(i>0){
                    SupervisorVO Total = new SupervisorVO();
                    Total.setCompanyName("小计：" + count);
                    resultData.add(Total);
                    sum+=count;
                }
                companyNameSearchId = list.get(i).getCompanyId();
                count = 1;
            }else{
                count++;
            }
            resultData.add(list.get(i));
        }
        sum+=count;
        SupervisorVO LastTotal = new SupervisorVO();
        LastTotal.setCompanyName("小计：" + count);
        resultData.add(LastTotal);

        SupervisorVO SumTotal = new SupervisorVO();
        SumTotal.setCompanyName("总计：" + sum);
        resultData.add(SumTotal);


        reportVO.setData(resultData);
        reportReturnVO.setGrids(reportVO);
        return reportReturnVO;
    }

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public boolean submit(Supervisor supervisor) {
        if (supervisor.getId() == null){
            supervisor.setFormType(String.valueOf(FormTypeConstant.HR_SUPERVISOR_FORM));
        }
        StaffFilesVO staffFilesVO = supervisor.getStaffFilesVO();
        if (supervisor.getIsOutSupervisor() == 1 && Optional.ofNullable(staffFilesVO).isPresent()){
            StaffFiles staffFiles = new StaffFiles();
            BeanUtils.copyProperties(staffFilesVO, staffFiles);
            staffFiles.setIsOut(2);
            staffFiles.setPersonnelType(2);
            if (StringUtil.isNotBlank(staffFiles.getStaffCode())) {
                staffFiles.setStaffCode(EncryptUtil.encryptBase64(staffFiles.getStaffCode(), BASE64_KEY));
            }
            if (StringUtil.isNotBlank(staffFiles.getDocumentNumber())) {
                staffFiles.setDocumentNumber(EncryptUtil.encryptBase64(staffFiles.getDocumentNumber(), BASE64_KEY));
            }
            boolean result = staffFilesService.saveOrUpdate(staffFiles);
            if(result) {
                staffFilesVO.setId(staffFiles.getId());
                staffFilesService.saveChild(staffFilesVO);
            }

        }
        supervisor.setStaffFilesId(staffFilesVO.getId());
        supervisor.setCompanyId(staffFilesVO.getCompanyNameId());
        supervisor.setBirthday(staffFilesVO.getBirthday());
        supervisor.setGenderId(staffFilesVO.getGenderId());
        supervisor.setStaffName(staffFilesVO.getStaffName());
        supervisor.setAppointmentTime(staffFilesVO.getCompanyInitiationTime());
        return saveOrUpdate(supervisor);
    }

    @Override
    public R<SupervisorVO> getDetailObj(SupervisorVO supervisorVO) {
        if(!Optional.ofNullable(supervisorVO).isPresent()){
            return new R(CommonCode.FAIL);
        }
        StaffFilesVO staffFilesVO = staffFilesWrapper.entityToVO(staffFilesService.getById(supervisorVO.getStaffFilesId()));
        supervisorVO.setStaffFilesVO(staffFilesService.getDetailObj(staffFilesVO).getPageData());
        return R.data(supervisorVO);
    }

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public boolean deleteLogic(List<Long> ids) {
        List<Long> delStaffFilesIds = new ArrayList<>();
        for (Long id : ids) {
            Supervisor supervisor = getById(id);
            if (supervisor == null) {
                return false;
            }

            if (Optional.ofNullable(supervisor.getIsOutSupervisor()).isPresent()
                    && supervisor.getIsOutSupervisor() == 1
                    && Optional.ofNullable(supervisor.getStaffFilesId()).isPresent()){
                delStaffFilesIds.add(supervisor.getStaffFilesId());
            }
        }

        boolean result = super.deleteLogic(ids);
        if (result && CollectionUtil.isNotEmpty(delStaffFilesIds)){
            staffFilesService.deleteLogic(delStaffFilesIds);
        }
        return result;
    }

}
